package cn.dakaqi.open.api.v1;

import cn.dakaqi.entities.*;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.vo.response.ActivityDiaryVO;
import cn.dakaqi.vo.response.GroupVO;
import cn.dakaqi.vo.response.PlatformGroupVO;
import com.wordnik.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.MediaTypes;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/7.
 * 社团
 */
@RestController
@RequestMapping(value = "/api/v1/group")
@Api(value = "社团")
public class GroupRestController
{
    private static Logger logger = LoggerFactory.getLogger(GroupRestController.class);
    @Autowired
    GroupService groupService;
    @Autowired
    ActivityDiaryService activityDiaryService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    private GroupVolunteerService groupVolunteerService;
    @Autowired
    private GroupRecruitService groupRecruitService;
    @Autowired
    private GroupRecruitVolunteerService groupRecruitVolunteerService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private PlatformGroup2Service platformGroup2Service;
    @Autowired
    private OrganizationService organizationService;


    @RequestMapping(value = "/groupCode/{groupCode}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> getByGroupCode(@PathVariable("groupCode") String groupCode)
    {
        JsonResult result = new JsonResult();
        try
        {
            Map<String,Object> resultMap = new HashMap<String,Object>();
            Group group = this.groupService.findByGroupCode(groupCode);
            if (group == null)
            {
                String message = "社团不存在";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }

            Page<ActivityDiary> diaries = activityDiaryService.findByGroupCode(groupCode, 99,1);
            List<ActivityDiaryVO> vos = new ArrayList<ActivityDiaryVO>();
            if(null != diaries && diaries.getContent() != null && diaries.getContent().size()>0)
            {
                for(ActivityDiary aa:diaries.getContent())
                    vos.add(ActivityDiaryVO.buildVO(aa));
            }

            GroupVO vo = GroupVO.buildVO(group,ConfigUtil.getClientId());
            //查询当前社团成员待审核数
            int count = groupVolunteerService.counts(vo.getGroupId(), DKQConstant.APPLY_STATUS);
            vo.setWaiteVerifers(count);

            //当前社团招募待审核数
            GroupRecruit groupRecruit = groupRecruitService.findLastByGroupCode(vo.getGroupCode(),DKQConstant.PROCEED_START);
            if(null != groupRecruit)
            {
                List<GroupRecruitVolunteer> list = this.groupRecruitVolunteerService.findVerfierByGroupRecruit(groupRecruit.getId(),DKQConstant.APPLY_STATUS);
                if(null != list)
                    vo.setWaiteRecruits(list.size());
            }
            resultMap.put("group", vo);
            resultMap.put("diaries", vos);
            result.setData(resultMap);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/id/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> getById(@PathVariable("id") Long id)
    {
        JsonResult result = new JsonResult();
        try
        {
            Group group = this.groupService.findOne(id);
            if (group == null)
            {
                String message = "社团不存在";
                logger.warn(message);
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put("group", GroupVO.buildVO(group,ConfigUtil.getClientId()));
            result.setData(resultMap);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> create(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
            //BeanValidators.validateWithException(validator, user);
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            this.groupService.save(param, ConfigUtil.getClientId());
            result.setMessage("社团创建成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }

        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/searhName/{name}/{pageNumber}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> searhName(@PathVariable("name") String name,@PathVariable("pageNumber") int pageNumber)
    {
        JsonResult result = new JsonResult();
        try
        {
            logger.info(name);
            // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
            //BeanValidators.validateWithException(validator, user);
            //检查非空
            if(StringUtils.isBlank(name))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            Page<Group> data = this.groupService.searchByName(name,pageNumber);
            Map<String,Object> resultMap = new HashMap<String,Object>();
            List<GroupVO> vos = new ArrayList<GroupVO>();
            if(null != data && null != data.getContent() && data.getContent().size()>0)
            {
                for(Group group:data.getContent())
                    vos.add(GroupVO.buildVO(group,ConfigUtil.getClientId()));
            }
            resultMap.put("list", vos);
            result.setData(resultMap);
            result.setMessage("查询成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/dissolve", method = RequestMethod.POST, consumes = MediaTypes.JSON,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> dissolve(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            logger.info(param);
            // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
            //BeanValidators.validateWithException(validator, user);
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            this.groupService.dissolve(param);
            result.setMessage("社团解散成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/joinOrg", method = RequestMethod.POST, consumes = MediaTypes.JSON,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> joinOrg(@RequestBody String param)
    {
        JsonResult result = new JsonResult();
        try
        {
            logger.info(param);
            // 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
            //BeanValidators.validateWithException(validator, user);
            //检查非空
            if(StringUtils.isBlank(param))
            {
                String message = "数据不能为空";
                result.setMessage(message);
                result.setCode(JsonResult.CODE_FAIL);
                return new ResponseEntity(result,HttpStatus.OK);
            }
            this.groupService.joinOrg(param);
            result.setMessage("等待上级审核");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }

        return new ResponseEntity(result,HttpStatus.OK);
    }

    @RequestMapping(value = "/joinOrgs/{groupCode}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> joinOrgs(@PathVariable("groupCode") String groupCode)
    {
        JsonResult result = new JsonResult();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<PlatformGroupVO> vos = new ArrayList<PlatformGroupVO>();
        try
        {
            Group group = this.groupService.findByGroupCode(groupCode);
            List<PlatformGroup> list = platformGroup2Service.findByGroup(group.getId());

            if(null != list && list.size()>0)
            {
                for(PlatformGroup pg:list)
                {
                    Platform platform = platformService.findOne(pg.getPlatformId());
                    Organization org = organizationService.findByOnePass(pg.getParentCode());
                    if(null != org && null != platform)
                    {
                        PlatformGroupVO vo = new PlatformGroupVO();
                        vo.setPlatformName(platform.getName());
                        vo.setParentName(org.getOrgname());
                        vo.setParentCode(org.getOnepass());
                        vo.setStatus(pg.getStatus());
                        vos.add(vo);
                    }
                }
            }
            resultMap.put("list", vos);
            result.setData(resultMap);
            result.setMessage("查询成功");
            result.setCode(JsonResult.CODE_SUCCESS);

        } catch (ConstraintViolationException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity(result,HttpStatus.OK);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }catch (Exception e)
        {
            e.printStackTrace();
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            return new ResponseEntity(result,HttpStatus.OK);
        }
        return new ResponseEntity(result,HttpStatus.OK);
    }

}
